package com.example.hrandroidapp;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import lib.jason.requestresponsetask.HTTPUtils;
import lib.jason.requestresponsetask.JSONHTTPPoster;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.type.TypeFactory;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.hrandroidapp.adapter.CustomSpinnerAdapter;
import com.example.hrandroidapp.common.Constant;
import com.example.hrandroidapp.common.DateUtils;
import com.example.hrandroidapp.common.HRLog;
import com.example.hrandroidapp.components.MMEditText;
import com.example.hrandroidapp.domain.LeaveType;
import com.example.hrandroidapp.fragment.DatePickerFragment;
import com.example.hrandroidapp.fragment.TimePickerFragment;
import com.example.hrandroidapp.fragment.TimePickerFragment.TimePickerValueCallBack;
import com.example.hrandroidapp.preferences.CurrentServerPreference;
import com.example.hrandroidapp.preferences.UserPreference;
import com.gc.materialdesign.widgets.Dialog;

public class CreateLeaveActivity extends ActionBarActivity implements DatePickerFragment.DatePickerValueCallBack,
								TimePickerValueCallBack{

	private Spinner spinner;
	private CustomSpinnerAdapter adapter;
	private TextView tvStartDate, tvEndDate, tvStartTime, tvEndTime;
	private MMEditText mmEtReason;
	private int dateStartEnd = 0;  // 1 for start, 2 for end
	private int timeStartEnd = 0;  // 1 for start, 2 for end
	private String url=null;
	
	private Date startDate, endDate;
	private TimePickerValueCallBack timeCallback;
	
	private ArrayList<LeaveType> lstLeaveType;
	private Long selectedLeaveType;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.new_leave);
		
		loadViews(); 
		
		tvStartDate.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				showDatePickerDialog(v);
				dateStartEnd = 1;
			}
		});
		
		tvEndDate.setOnClickListener(new OnClickListener() {
					
			@Override
			public void onClick(View v) {
				showDatePickerDialog(v);
				dateStartEnd = 2;
			}
		});

		tvStartTime.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				showTimePickerDialog(v);
				timeStartEnd = 1;
			}
		});

		tvEndTime.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				showTimePickerDialog(v);
				timeStartEnd = 2;
			}
		});
		
		spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				selectedLeaveType = lstLeaveType.get(position).getLeaveTypeID();
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {}
		});
		
		loadLeaveTypes(); 
	}
	
	private void loadViews() {
		spinner = (Spinner) findViewById(R.id.leave_type_spinner);
		tvStartDate = (TextView) findViewById(R.id.tv_start_date);
		tvEndDate = (TextView) findViewById(R.id.tv_end_date);
		tvStartTime = (TextView) findViewById(R.id.tv_start_time);
		tvEndTime = (TextView) findViewById(R.id.tv_end_time);
		mmEtReason = (MMEditText) findViewById(R.id.et_reason);
		lstLeaveType = new ArrayList<LeaveType>();
	}
	
	@Override
	public void onBackPressed() {
		super.onBackPressed();
		overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.new_leave_menu, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		
		if(id == R.id.action_send) {
			leaveApply(); 
		}else if(id == android.R.id.home) {
			onBackPressed();
		}
		
		return super.onOptionsItemSelected(item);
	}
	
	private void loadLeaveTypes() {

		url = getResources().getString(R.string.leave_type_url);
		String completeUrl = "http://" + CurrentServerPreference.getCurrentServer(this).getSvrIP() + ":" + Constant.PORT + url;
		
		new HTTPUtils(this, JSONHTTPPoster.MEDIA_FORM_URLENCODED, completeUrl, "", 
				new HTTPUtils.SimpleRequestResponseTaskInterface() {

			@Override
			public void handleResponse(String responseStr, int status) throws Exception {
				
				ObjectMapper mapper = new ObjectMapper();
				
				lstLeaveType = mapper.readValue(responseStr, TypeFactory.collectionType(List.class, LeaveType.class));
				selectedLeaveType = lstLeaveType.get(0).getLeaveTypeID();
				adapter = new CustomSpinnerAdapter(CreateLeaveActivity.this, R.layout.leave_type_spinner, lstLeaveType);
				spinner.setAdapter(adapter);

			}
			
		}).execute();
		
	}
	
	private void leaveApply() {

		url = getResources().getString(R.string.leave_apply_url);
		String completeUrl = "http://" + CurrentServerPreference.getCurrentServer(this).getSvrIP() + ":" + Constant.PORT + url;
		
		JSONObject jsonObj = new JSONObject();
		try {
			jsonObj.put("loginId", UserPreference.getLoginId(this));
			jsonObj.put("createdBy", UserPreference.getUserId(this));
			jsonObj.put("startDateTime", tvStartDate.getText().toString().replace("-", ""));
			jsonObj.put("endDateTime", tvEndDate.getText().toString().replace("-", ""));
			jsonObj.put("leaveType", selectedLeaveType.toString());
			jsonObj.put("reason", mmEtReason.getText().toString());
		} catch (JSONException e) {
			e.printStackTrace();
		}

		String paramString = jsonObj.toString();	
		
		HRLog.postLogInfo("leave apply url complete: " + completeUrl, " at CreateLeaveActivity.leaveApply"); 
		new HTTPUtils(this, JSONHTTPPoster.MEDIA_JSON_TYPE, completeUrl, paramString, 
				new HTTPUtils.SimpleRequestResponseTaskInterface() {

			@Override
			public void handleResponse(String responseStr, int status) throws Exception {
				HRLog.postLogDebug("response status: " + status, " at CreateLeaveActivity.leaveApply");
				if(status == 200) {
					Toast.makeText(getBaseContext(),"Leave send successfully...",Toast.LENGTH_LONG).show();
					finish(); 
				}else {
					Toast.makeText(getBaseContext(),"Leave send Fail!!",Toast.LENGTH_LONG).show();
				}
			}
			
		}).execute();
	}
	
	public void showTimePickerDialog(View v) {
	    DialogFragment newFragment = new TimePickerFragment(this);
	    newFragment.show(getSupportFragmentManager(), "timePicker");
	}
	
	public void showDatePickerDialog(View v) {
	    DialogFragment newFragment = new DatePickerFragment(this);
	    newFragment.show(getSupportFragmentManager(), "datePicker");
	}
	

	public static interface TimePickerValueCallBack {
		void returnTimePickerValue();
	}


	@Override
	public void returnDatePickerValue(int year, int month, int day) {
		Integer value = (year * 10000) + (++month * 100) + day;
		switch(dateStartEnd) {
		case 1:
			tvStartDate.setText(DateUtils.getDateInString(year, month, day, DateUtils.DATE_YYYYMMDD_FORMAT));
			startDate = DateUtils.convert(value, DateUtils.DATE_YYYYMMDD_FORMAT); 
			break;
		case 2:
			endDate = DateUtils.convert(value, DateUtils.DATE_YYYYMMDD_FORMAT);
			if(endDate.before(startDate)) {
				Dialog dialog = new Dialog(this, "Invalid Date", "End date should be after start date...", "OK", "", true, false);
				dialog.setOnCancelButtonClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {}
				});
				dialog.show();
			}else {
				tvEndDate.setText(DateUtils.getDateInString(year, month, day, DateUtils.DATE_YYYYMMDD_FORMAT));
			}
			break;
		}
		dateStartEnd = 0;
	}

	@Override
	public void returnTimePickerValue(int hourOfDay, int minute) {
		switch(timeStartEnd) {
		case 1:
			tvStartTime.setText(DateUtils.getHourMinInString(hourOfDay, minute));
			break;
		case 2:
			tvEndTime.setText(DateUtils.getHourMinInString(hourOfDay, minute));
			break;
		}
		timeStartEnd = 0;
	}
}
